import 'dart:io';
import 'package:dio/dio.dart';
import 'package:dio/io.dart';
import 'package:flutter/foundation.dart';
import 'package:laos_mall/pages/main/config.dart';

import 'my_interceptor.dart';

class Http {
  final String baseUrl = 'http://dev.mabillon.shop';

  static final Http _instance = Http._();
  static Http get instance => Http();
  factory Http() => _instance;
  static late Dio _dio;
  Dio get dio => _dio;
  Http._() {
    // 构造 Dio options
    final BaseOptions options = BaseOptions(
      contentType: ContentType.json.toString(),
      sendTimeout: const Duration(seconds: 8),
      responseType: ResponseType.json,
      validateStatus: (_) => true,
      baseUrl: baseUrl,
      headers: Config.httpHeader
    );
    _dio = Dio(options);
    // 忽略 https 证书校验
    if (kIsWeb) {
    } else {
      _dio.httpClientAdapter = IOHttpClientAdapter(
        createHttpClient: () {
          final client = HttpClient();
          client.badCertificateCallback =
              (X509Certificate cert, String host, int port) {
            return true; // Verify the certificate.
          };
          return client;
        },
      );
    }
    _dio.interceptors.add(MyInterceptor());
  }

  String getError(Object obj) {
    debugPrint(obj.toString());
    switch (obj.runtimeType) {
      case DioException:
        if ((obj as DioException).type == DioExceptionType.unknown) {
          return '未知错误';
        } else if (obj.type == DioExceptionType.connectionError) {
          return '连接异常';
        }
    }
    return '服务器错误';
  }
}
